package com.qdlc.p2p.manage.action.additional;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.qdlc.p2p.dal.dao.*;
import com.qdlc.p2p.dal.dto.*;
import com.qdlc.p2p.dal.model.CashAwardRuleModel;
import org.apache.struts2.convention.annotation.Action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.NewActivityPlanService;
import com.qdlc.p2p.biz.service.NewActivityRuleService;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.util.BeanUtil;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.model.NewActivityRuleModel;

/**
 * Created by liaoxiangkai on 2015/11/28.
 */
public class ManageNewActivityRuleAction extends BaseAction<NewActivityRuleModel> implements ModelDriven<NewActivityRuleModel> {
    @Resource
    private NewActivityRuleService newActivityRuleService;
    @Resource
    private NewActivityPlanService newActivityPlanService;

    private NewActivityRuleModel model = new NewActivityRuleModel();

    public NewActivityRuleModel getModel() {
        return model;
    }

    private Map<String, Object> data;

    /**
     * ---------------活动规则主页---------------------
     * 进入页面
     *
     * @return String
     * @throws Exception
     */
    @Action("/modules/additional/newActivityRule/newActivityRuleManager")
    public String newActivityRuleManager() throws Exception {
        return "newActivityRuleManager";
    }

    /**
     * 列表
     *
     * @throws Exception
     */
    @Action("/modules/additional/newActivityRule/newActivityRuleList")
    public void newActivityRuleList() throws Exception {
        data = new HashMap<String, Object>();
        PageDataList<NewActivityRuleModel> pageDataList = newActivityRuleService.list(model);
        if (pageDataList == null) {
            return;
        }
        data.put("total", pageDataList.getPage().getTotal());
        data.put("rows", pageDataList.getList());
        printJson(getStringOfJpaObj(data));
    }

    /**
     * --------------------添加活动规则--------------------------
     * 进入页面
     *
     * @return
     * @throws Exception
     */
    @Action("/modules/additional/newActivityRule/newActivityRuleAddPage")
    public String newActivityRuleAddPage() throws Exception {
        return "newActivityRuleAddPage";
    }

    /**
     * 活动规则添加动作
     *
     * @throws Exception
     */
    @SuppressWarnings("static-access")
    @Action("/modules/additional/newActivityRule/newActivityRuleAdd")
    public void newActivityRuleAdd() throws Exception {
        //检测添加活动规则参数
        if (!checkNewActivityRule(model)) return;
        //保存红包方案
        Operator operator = getOperator();
        if (null == operator) {
            printResult("请先登录！", false);
            return;
        }
        model.setCreator(operator);
        model.setCreateTime(DateUtil.getNow());
        NewActivityRule newActivityRule = newActivityRuleService.save(model);
        if (newActivityRule == null) {
            printResult("添加活动规则失败！", false);
            return;
        }
        printResult("添加活动规则成功！", true);
    }

    /**
     * -------------------编辑活动规则-----------------------------
     * 进入页面
     *
     * @return String
     * @throws Exception
     */
    @Action("/modules/additional/newActivityRule/newActivityRuleEditPage")
    public String newActivityRuleEditPage() throws Exception {
        NewActivityRuleModel activityRule = newActivityRuleService.findByActivityRuleId(model.getId());
        if (activityRule == null) {
            printResult("该活动规则不存在!", false);
            return "newActivityRuleManager";
        }
        request.setAttribute("activityRule", activityRule);
        return "newActivityRuleEditPage";
    }

    /**
     * 活动规则更新动作
     *
     * @throws Exception
     */
    @Action("/modules/additional/newActivityRule/doNewActivityRuleEdit")
    public void donewActivityRuleEdit() throws Exception {
        //检测添加活动规则参数
        if (!checkNewActivityRule(model)) return;
        //更新活动规则
        Operator operator = getOperator();
        if (null == operator) {
            printResult("请先登录！", false);
            return;
        }
        model.setModifier(operator);
        model.setModifyTime(DateUtil.getNow());
        NewActivityRule newActivityRule = newActivityRuleService.update(model);
        if (null == newActivityRule) {
            printResult("修改活动规则失败！", false);
            return;
        }
        printResult("修改活动规则成功！", true);
    }

    /**
     * ----------------详情页面-------------------
     *
     * @return String
     * @throws Exception
     */
    @Action("/modules/additional/newActivityRule/newActivityRuleDetailPage")
    public String newActivityRuleDetailPage() throws Exception {
        NewActivityRuleModel activityRule = newActivityRuleService.findByActivityRuleId(model.getId());
        if (activityRule == null) {
            printResult("该活动规则不存在!", false);
            return "newActivityRuleManager";
        }
        request.setAttribute("activityRule", activityRule);
        return "newActivityRuleDetailPage";
    }

    /**
     * --------------------是否开启本条规则-----------------------
     * 开启规则
     *
     * @throws IOException
     */
    @Action("/modules/additional/newActivityRule/newActivityRuleEnable")
    public void newActivityRuleEnable() throws IOException {
        Operator operator = getOperator();
        if (null == operator) {
            printResult("请先登录！", false);
            return;
        }
        //设置更新者更新时间
        model.setModifier(operator);
        model.setModifyTime(DateUtil.getNow());
        int result = newActivityRuleService.toggleStatus(model);
        if (result > 0) {
            printWebSuccess();
        } else {
            printWebResult("启用失败，请确认活动规则是否已开启！", false);
        }
    }

    /**
     * 关闭规则
     *
     * @throws IOException
     */
    @Action("/modules/additional/newActivityRule/newActivityRuleDisable")
    public void newActivityRuleDisable() throws IOException {
        Operator operator = getOperator();
        if (null == operator) {
            printResult("请先登录！", false);
            return;
        }
        //设置更新者更新时间
        model.setModifier(operator);
        model.setModifyTime(DateUtil.getNow());
        int result = newActivityRuleService.toggleStatus(model);
        if (result > 0) {
            printWebSuccess();
        } else {
            printWebResult("关闭失败，请确认活动规则是否已关闭！", false);
        }
    }

    /**
     * ---------------------添加活动规则时异步查询活动及规则名称---------------------------
     * 初始化所有的活动名称
     */
    @Action("/modules/additional/newActivityRule/initActivitySelect")
    public void initActivitySelect() throws IOException {
        List<NewActivityPlan> list = newActivityPlanService.findEnablePlan();
        if (null != list && list.size() > 0) {
            JSONArray jsonArray = new JSONArray();//new一个json数组
            for (NewActivityPlan entity : list) {
                JSONObject obj = new JSONObject();
                obj.put("activity_id", entity.getId());
                obj.put("activity_name", entity.getName());
                jsonArray.add(obj);//循环new jsonObject
            }
            printJson(jsonArray.toString());
        }
    }

    /**
     * 异步加载规则类型对应的所有规则名称
     */
    @Action("/modules/additional/newActivityRule/initRuleNameSelect")
    public void initRuleNameSelect() throws IOException {
        int ruleType = paramInt("ruleType");
        JSONArray jsonArray = new JSONArray();//new一个json数组
        switch (ruleType) {
            case (1):
                RedEnvelopeDao redEnvelopeDao = (RedEnvelopeDao) BeanUtil.getBean("redEnvelopeDao");
                List<RedEnvelope> redEnvelopeList = redEnvelopeDao.findByCriteria(QueryParam.getInstance().addParam("status", 1));
                if (null != redEnvelopeList && redEnvelopeList.size() > 0) {
                    for (RedEnvelope entity : redEnvelopeList) {
                        JSONObject obj = new JSONObject();
                        obj.put("rule_id", entity.getId());
                        obj.put("rule_name", entity.getName());
                        jsonArray.add(obj);//循环new jsonObject
                    }
                    printJson(jsonArray.toString());
                    return;
                }
                break;
            case (2):
                ExperienceRuleDao experienceRuleDao = (ExperienceRuleDao) BeanUtil.getBean("experienceRuleDao");
                List<ExperienceRule> experienceRuleList = experienceRuleDao.findByCriteria(QueryParam.getInstance().addParam("status",1));
                if (null != experienceRuleList && experienceRuleList.size() > 0) {
                    for (ExperienceRule entity : experienceRuleList) {
                        JSONObject obj = new JSONObject();
                        obj.put("rule_id", entity.getId());
                        obj.put("rule_name", entity.getName());
                        jsonArray.add(obj);//循环new jsonObject
                    }
                    printJson(jsonArray.toString());
                    return;
                }
                break;
            case (3):
                RateRuleDao rateRuleDao = (RateRuleDao) BeanUtil.getBean("rateRuleDao");
                List<RateRule> rateRuleList = rateRuleDao.findByCriteria(QueryParam.getInstance().addParam("isUse", 1));
                if (null != rateRuleList && rateRuleList.size() > 0) {
                    for (RateRule entity : rateRuleList) {
                        JSONObject obj = new JSONObject();
                        obj.put("rule_id", entity.getId());
                        obj.put("rule_name", entity.getRuleName());
                        jsonArray.add(obj);//循环new jsonObject
                    }
                    printJson(jsonArray.toString());
                    return;
                }
                break;
            case (4):
                AdditionalDrawLotteryRuleDao lotteryRuleDao = (AdditionalDrawLotteryRuleDao) BeanUtil.getBean("additionalDrawLotteryRuleDao");
                List<AdditionalDrawLotteryRule> additionalDrawLotteryRuleList = lotteryRuleDao.findByCriteria(QueryParam.getInstance().addParam("status", 0));
                if (null != additionalDrawLotteryRuleList && additionalDrawLotteryRuleList.size() > 0) {
                    for (AdditionalDrawLotteryRule entity : additionalDrawLotteryRuleList) {
                        JSONObject obj = new JSONObject();
                        obj.put("rule_id", entity.getId());
                        obj.put("rule_name", entity.getName());
                        jsonArray.add(obj);//循环new jsonObject
                    }
                    printJson(jsonArray.toString());
                    return;
                }
                break;
            case (5):
                AdditionalMovieTicketRuleDao movieTicketRuleDao = (AdditionalMovieTicketRuleDao) BeanUtil.getBean("additionalMovieTicketRuleDao");
                List<AdditionalMovieTicketRule> additionalMovieTicketRuleList = movieTicketRuleDao.findByCriteria(QueryParam.getInstance().addParam("status", 0));
                if (null != additionalMovieTicketRuleList && additionalMovieTicketRuleList.size() > 0) {
                    for (AdditionalMovieTicketRule entity : additionalMovieTicketRuleList) {
                        JSONObject obj = new JSONObject();
                        obj.put("rule_id", entity.getId());
                        obj.put("rule_name", entity.getName());
                        jsonArray.add(obj);//循环new jsonObject
                    }
                    printJson(jsonArray.toString());
                    return;
                }
                break;
            case (6):
                CashAwardRuleDao cashAwardRuleDao = (CashAwardRuleDao) BeanUtil.getBean("cashAwardRuleDao");
                List<CashAwardRule> cashAwardRuleList = cashAwardRuleDao.findByStatus(CashAwardRuleModel.CASH_AWARD_RULE_STATUS_ENABLE);
                if (null != cashAwardRuleList
                        && cashAwardRuleList.size() > 0) {
                    for (CashAwardRule entity : cashAwardRuleList) {
                        JSONObject obj = new JSONObject();
                        obj.put("rule_id", entity.getId());
                        obj.put("rule_name", entity.getName());
                        jsonArray.add(obj);
                    }
                    printJson(jsonArray.toString());
                    return;
                }
                break;
            case (7):
            	WineCouponsDao wineCouponsDao = (WineCouponsDao) BeanUtil.getBean("wineCouponsDao");
                List<WineCoupons> wineCouponsList = wineCouponsDao.findByCriteria(QueryParam.getInstance().addParam("status", 1));
                if (null != wineCouponsList && wineCouponsList.size() > 0) {
                    for (WineCoupons entity : wineCouponsList) {
                        JSONObject obj = new JSONObject();
                        obj.put("rule_id", entity.getId());
                        obj.put("rule_name", entity.getName());
                        jsonArray.add(obj);//循环new jsonObject
                    }
                    printJson(jsonArray.toString());
                    return;
                }
                break;
        }
        printJson(jsonArray.toString());
    }


    /**
     * ------------------校验方法-----------------------
     * 检验添加活动规则参数
     *
     * @param model
     * @return boolean
     */
    private boolean checkNewActivityRule(NewActivityRuleModel model) throws Exception {
        if (model.getActivityId() <= 0) {
            printWebResult("请选择活动类型！", false);
            return false;
        }
        if (model.getType() <= 0) {
            printWebResult("请选择规则类型！", false);
            return false;
        }
        if (model.getRuleId() <= 0) {
            printWebResult("请选择规则名称！", false);
            return false;
        }
        if (StringUtil.isBlank(model.getStartTime())) {
            printWebResult("请填写活动规则开始时间！", false);
            return false;
        }
        if (StringUtil.isBlank(model.getEndTime())) {
            printWebResult("请填写活动规则结束时间！", false);
            return false;
        }
        return true;
    }
}
